using System;
using System.Collections.Generic;
using System.Text;
using CodePlex.Resourceful;
using CodePlex.SpaceBlock.FS;
using CodePlex.Resourceful.Amazon.S3;

namespace CodePlex.SpaceBlock.UI
{
    public class FileSystemManager
    {

        private readonly ReadOnlyList<FileSystemInfo> _fileSystemInfos;
        private ReadOnlyList<IFileSystem> _fileSystems;

        public FileSystemManager(IEnumerable<FileSystemInfo> infos)
        {
            _fileSystemInfos=  new ReadOnlyList<FileSystemInfo>(infos);

            try
            {
                _fileSystems = _fileSystemInfos.ConvertAll<IFileSystem>(this.ToFileSystem);
            }
            catch { }
        }


        public bool IsValid
        {
            get
            {
                return _fileSystems != null;
            }
        }

        public ReadOnlyList<IFileSystem> FileSystems
        {
            get
            {
                return _fileSystems;
            }
        }

        public ReadOnlyList<FileSystemInfo> FileSystemInfos
        {
            get
            {
                return _fileSystemInfos;
            }
        }


        public IFileSystem ToFileSystem(FileSystemInfo info)
        {
            if (info.Type == "Local")
            {
                return new LocalFileSystem();
            }
            if (info.Type == "S3")
            {
                string accessKeyID = info.PublicSettings.GetIfExists(UIConstants.S3Settings.AWSAccessKeyID);
                string secretAccessKey = info.PrivateSettings.GetIfExists(UIConstants.S3Settings.AWSSecretAccessKey);
                string useSSL = info.PublicSettings.GetIfExists(UIConstants.S3Settings.UseSSL);

                S3Connection cn = new S3Connection(accessKeyID, secretAccessKey, useSSL == true.ToString(), RequestStyle.VHost);
                return new S3FileSystem(cn);
            }

            throw CodePlexException.Format(Properties.Messages.Exceptions_UnknownFileSystem, info.Type);

        }

    }
}
